/*
  ******************************************************************************
  * @file    usb_demo.c
  * @author  FreqChip Firmware Team
  * @version V1.0.0
  * @date    2021
  * @brief   USB module Demo.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2021 FreqChip.
  * All rights reserved.
  ******************************************************************************
*/
#include "usb_demo.h"
#include "driver_pmu.h"

#include "co_printf.h"
#include "co_log.h"

#include "usb_cdc.h"

uint8_t TransUSB_Buffer[512];

/*********************************************************************
 * @fn      Endpoint1_Handler
 *
 * @brief   endpoint1 RX TX Handler
 *
 * @param   None.
 * @return  None.
 */
static void Endpoint1_Handler(uint8_t RxStatus, uint8_t TxStatus)
{
    uint8_t lu8_RxCount;
    if (RxStatus & ENDPOINT_1_MASK) 
    {
        usb_selecet_endpoint(ENDPOINT_1);

        lu8_RxCount = usb_Endpoints_get_RxCount();

        usb_read_fifo(ENDPOINT_1, TransUSB_Buffer, lu8_RxCount);

        usb_Endpoints_FlushRxFIFO();


        if (usb_Endpoints_GET_TxPkrRdy() == false) 
        {
            usb_write_fifo(ENDPOINT_1, TransUSB_Buffer, lu8_RxCount);
            
            usb_Endpoints_SET_TxPktRdy();
        }
    }
}

/*********************************************************************
 * @fn      usb_dev_Transparentmission_Init
 *
 * @brief   Transparent transmission parameter initialization 
 *
 * @param   None.
 * @return  None.
 */
void usb_dev_Transparentmission_Init(void)
{    
    Endpoints_Handler = Endpoint1_Handler;    
    USB_Reset_Handler = usb_dev_Transparentmission_Init;
    
    /* config data endpoint fifo */
    usb_selecet_endpoint(ENDPOINT_1);   // 64Byte
    usb_endpoint_Txfifo_config(64/8, 3);
    usb_endpoint_Rxfifo_config(128/8, 3);
    usb_TxMaxP_set(8);
    usb_RxMaxP_set(8);
    
    usb_RxInt_Enable(ENDPOINT_1);    
}   

/*********************************************************************
 * @fn      usb_dev_custom
 *
 * @brief   User device customization
 *
 * @param   None.
 * @return  None.
 */
void usb_dev_custom(void)
{
    pmu_usb_pad_ctrl(true);
    
    NVIC_ClearPendingIRQ(USBMCU_IRQn);
    NVIC_SetPriority(USBMCU_IRQn, 0);
    NVIC_EnableIRQ(USBMCU_IRQn);
    
	usb_device_init();
	usb_dev_Transparentmission_Init();

	usb_DP_Pullup_Enable();
    
    while(1);
}    


